"""
日志模块
提供统一的日志记录功能
"""

import logging
import os
from typing import Optional


def get_logger(name: str, log_file: str = "app.log", level: int = logging.INFO) -> logging.Logger:
    """
    获取日志记录器
    
    Args:
        name: 日志记录器名称
        log_file: 日志文件路径
        level: 日志级别
        
    Returns:
        配置好的日志记录器
    """
    logger = logging.getLogger(name)
    
    # 如果已经配置过，直接返回
    if logger.handlers:
        return logger
        
    logger.setLevel(level)
    
    # 创建文件日志处理器
    file_handler = logging.FileHandler(log_file, encoding="utf-8")
    file_handler.setLevel(level)
    
    # 创建控制台日志处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    
    # 定义日志格式
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger


class Logger:
    """
    日志记录器类
    提供更方便的日志记录接口
    """
    
    def __init__(self, name: str = "ragflow_client", log_file: str = "app.log", level: int = logging.INFO):
        """
        初始化日志记录器
        
        Args:
            name: 日志记录器名称
            log_file: 日志文件路径
            level: 日志级别
        """
        self.logger = get_logger(name, log_file, level)
    
    def log(self, level: str, *args) -> None:
        """
        记录日志，支持多个参数
        
        Args:
            level: 日志级别（DEBUG, INFO, WARNING, ERROR, CRITICAL）
            args: 任意类型的日志信息
        """
        message = " ".join(map(str, args))
        
        if level == "DEBUG":
            self.logger.debug(message)
        elif level == "INFO":
            self.logger.info(message)
        elif level == "WARNING":
            self.logger.warning(message)
        elif level == "ERROR":
            self.logger.error(message)
        elif level == "CRITICAL":
            self.logger.critical(message)
        else:
            raise ValueError(f"不支持的日志级别: {level}")
    
    def debug(self, *args) -> None:
        """记录调试级别日志"""
        self.log("DEBUG", *args)
    
    def info(self, *args) -> None:
        """记录信息级别日志"""
        self.log("INFO", *args)
    
    def warning(self, *args) -> None:
        """记录警告级别日志"""
        self.log("WARNING", *args)
    
    def error(self, *args) -> None:
        """记录错误级别日志"""
        self.log("ERROR", *args)
    
    def critical(self, *args) -> None:
        """记录严重错误级别日志"""
        self.log("CRITICAL", *args)


# 创建默认日志记录器
default_logger = Logger(
    name="ragflow_client",
    log_file="app.log",
    level=logging.DEBUG if os.getenv("DEBUG", "false").lower() == "true" else logging.INFO
)